package com.lx.util;//说明:


import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 创建人:游林夕/2019/3/27 14 45
 */
class LXHttp {
    static String doGet(String url, Map<String, String> property) {
        return http(url,"GET", null, property,30000,null);
    }
    static InputStream doGetStream(String url, Map<String, String> property) {
        return httpInputStream(url,"GET", null, property,30000,null);
    }
    static String doPost(String url, String json) {
        return doPost(url,json,null);
    }
    static String doPost(String url, String json, Map<String, String> property){
        return http(url,"POST", json, property,30000,null);
    }
    static String doPost(String url, String json, Map<String, String> property, int timeout) {
        return http(url,"POST", json, property,timeout,null);
    }
    static InputStream doPostInputStream(String url, String json, Map<String, String> property){
        return httpInputStream(url,"POST", json, property,30000,null);
    }

    static String doSSLPost(String url, String json, SSLSocketFactory sslSocketFactory) {
        return doSSLPost(url,json,null, sslSocketFactory);
    }
    static String doSSLPost(String url, String json, Map<String, String> property, SSLSocketFactory sslSocketFactory){
        return http(url,"POST", json, property,30000,sslSocketFactory);
    }


    public static String http(String urlStr, String method, String json, Map<String, String> property, int timeout, SSLSocketFactory sslSocketFactory){
        try(BufferedReader br = new BufferedReader(new InputStreamReader(httpInputStream(urlStr, method, json, property, timeout,sslSocketFactory), "utf-8"))){
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        }catch (Exception e){
            LX.exMsg(e);
        }
        return null;
    }
    public static InputStream httpInputStream(String urlStr, String method, String json, Map<String, String> property, int timeout, SSLSocketFactory sslSocketFactory){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            if (sslSocketFactory != null){
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier((hostname, sslSession) -> true);
                https.setSSLSocketFactory(sslSocketFactory);
                connection = https;
            }else{
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setRequestMethod(method);
            // 设置默认Content-Type
            connection.setRequestProperty("Content-Type", "application/json");
            if (LX.isNotEmpty(property)){
                for (Map.Entry<String, String> e : property.entrySet()){
                    connection.setRequestProperty(e.getKey() ,e.getValue());
                }
            }
            // 设置是否向httpUrlConnection输出，post请求设置为true，默认是false
            connection.setDoOutput("POST".equals(method.toUpperCase()));
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            if("POST".equals(method.toUpperCase())){
                try(PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"))){
                    printWriter.write(json);
                    printWriter.flush();
                }
            }
            // 返回结果-字节输入流转换成字符输入流，控制台输出字符
            if (connection.getResponseCode() == 200){
                return connection.getInputStream();
            }else{
                return connection.getErrorStream();
            }
        }catch (Exception e){
            LX.exMsg(e);
        }
        return null;
    }

    static {
        try {
            //https 默认信任证书
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier((urlHostName, session) -> true);
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
    }

}
